package com.hunttown.mes.manage.shiro.token;

import com.hunttown.mes.common.keys.KeyConstants;
import com.hunttown.mes.common.utils.SpringContextUtil;
import com.hunttown.mes.manage.cache.ManageRightMenuCacheData;
import com.hunttown.mes.manage.service.AnalysisManageManageService;
import com.hunttown.mes.rpc.domain.AnalysisManageDTO;
import com.hunttown.mes.rpc.domain.AnalysisManageRightMenuDTO;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class LoginAuthorRealm extends AuthorizingRealm {

    public LoginAuthorRealm() {
        super();
    }

    /**
     * 认证信息，主要针对用户登录，
     */
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {

        // 此处不再做用户认证 直接返回
        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
        String pin = token.getUsername();
        AnalysisManageManageService manageService = SpringContextUtil.getBeanByType(AnalysisManageManageService.class);
        AnalysisManageDTO user = manageService.getFromCachePin(pin);
        SecurityUtils.getSubject().getSession().setAttribute(KeyConstants.LOGIN_SESSION_ADMIN + pin, user);
        System.out.println("shiro doGetAuthenticationInfo : " + pin);
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(pin, "", getName());
        return simpleAuthenticationInfo;
    }

    /**
     * 授权
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        String pin = (String) getAvailablePrincipal(principals);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        // 根据用户ID查询权限（permission），放入到Authorization里。
        AnalysisManageManageService manageService = SpringContextUtil.getBeanByType(AnalysisManageManageService.class);
        List<Integer> menuIds = manageService.getMenuIdListByAdminName(pin);
        Set<String> permissions = new HashSet<>();
        for (Integer id : menuIds) {
            AnalysisManageRightMenuDTO menu = ManageRightMenuCacheData.getMenuById(id);
            // 只放有 menu_path 的请求就可以
            if (menu != null && menu.getMenuPath() != null && !menu.getMenuPath().equals("#") && !menu.getMenuPath().trim().equals("")) {
                permissions.add(menu.getMenuPath());
            }
        }
        info.setStringPermissions(permissions);
        return info;
    }

    /**
     * 清空当前用户权限信息
     */
    public void clearCachedAuthorizationInfo() {
        PrincipalCollection principalCollection = SecurityUtils.getSubject().getPrincipals();
        SimplePrincipalCollection principals = new SimplePrincipalCollection(
                principalCollection, getName());
        super.clearCachedAuthorizationInfo(principals);
    }

    /**
     * 指定principalCollection 清除
     */
    public void clearCachedAuthorizationInfo(PrincipalCollection principalCollection) {
        SimplePrincipalCollection principals = new SimplePrincipalCollection(
                principalCollection, getName());
        super.clearCachedAuthorizationInfo(principals);
    }
}
